package login

import (
	"fmt"
	"github.com/spf13/viper"
	"go-interview-forum/db/redis"
	"go-interview-forum/global"
	"go-interview-forum/model/user"
	"go-interview-forum/pkg"
	"log"
	"strconv"
	"time"
)

func UserLogin(mobile, code string) (string, error) {
	exists, err := redis.Exists(global.SMS_LOGIN + mobile)
	if err != nil {
		return "", err
	}

	if exists == 0 {
		return "", fmt.Errorf("请发送验证码")
	}

	var rCode string
	err = redis.GetKey(global.SMS_LOGIN+mobile, &rCode)
	if err != nil {
		return "", err
	}

	//判断验证码是否正确
	if rCode != code {
		return "", fmt.Errorf("验证码错误")
	}

	err = redis.DelKey(global.SMS_LOGIN + mobile)
	if err != nil {
		return "", err
	}

	userInfo := user.User{Mobile: mobile}
	err = user.GetUserByMobile(&userInfo)
	if err != nil {
		log.Println(err)
		return "", err
	}

	if userInfo.ID == 0 {
		userInfo.Nickname = fmt.Sprintf("用户%s****%s", mobile[:3], mobile[7:])

		_err := user.CreatedUser(&userInfo)
		if _err != nil {
			return "", _err
		}
	}

	secret := viper.GetString("jwt.secret")
	expire, _ := strconv.Atoi(viper.GetString("jwt.expire"))
	token, err := pkg.GetJwtToken(secret, time.Now().Unix(), int64(expire), strconv.Itoa(int(userInfo.ID)))
	if err != nil {
		log.Println(err)
		return "", err
	}

	return token, err
}
